package com.diy.sigmund.diycommon.util.seq;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 参考：https://blog.csdn.net/qq_36903261/article/details/107045717
 * 未解决时钟回拨问题
 *
 * @author ylm-sigmund
 * @since 2021/7/3 16:45
 */
public class SeqUtil {

    private static final Logger LOG = LoggerFactory.getLogger(SeqUtil.class);

    /** 第几号机房：worker Id can't be greater than 31 or less than 0 **/
    private static long workerId = 0;
    /** 第几号机器 **/
    private static long dataCenterId = 1;

    /*static {
        try {
            //获取本机的ip地址编码
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
            // 当前机器的workerId: 3232240897
            LOG.info("当前机器的workerId: " + workerId);
        } catch (Exception e) {
            LOG.warn("当前机器的workerId获取失败 ----> " + e);
            workerId = NetUtil.getLocalhostStr().hashCode();
        }
    }*/

    /** 获取单例的Twitter的Snowflake 算法生成器对象 **/
    private static final Snowflake SNOWFLAKE = IdUtil.getSnowflake(workerId, dataCenterId);

    /**
     * 长度19位
     */
    public static synchronized String snowflakeId() {
        return String.valueOf(SNOWFLAKE.nextId());
    }

    public static synchronized String getRequestId() {
        return String.valueOf(System.nanoTime());
    }

    //测试
    public static void main(String[] args) {
        System.out.println(snowflakeId());
    }
}
